//
//  JCTabBarItem.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/15.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit

class JCTabBarItem: UITabBarItem {
    //底部tabbaritem的  下标
//    var index: Int = 0
    
    
   override var badgeValue: String? {
    didSet{
        //设置 badgeValue后 会调用
        
        setBadgeValueBackImage()
    }
}

private func setBadgeValueBackImage(){
    //获取  tabBarController   显示badgeValue
    let target = self.valueForKeyPath("_target") as! UITabBarController
    
    
    //重写badgeValue的set方法
    //拿到tabbar子视图
//    for tabbarChild in self.tabBarController!.tabBar.subviews{
    for tabbarChild in target.tabBar.subviews{
        //拿到UITabBarButton
        if tabbarChild.isKindOfClass(NSClassFromString("UITabBarButton")!){
            // 拿到UITabBarButton 子视图
            for tabbarbtnChild in tabbarChild.subviews{
                //拿到_UIBadgeView
                if tabbarbtnChild.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                    for badgeViewChild in tabbarbtnChild.subviews{
                        if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!){
                            printLog("设置badgeValue Set方法")
                            //重写badgeValue  set方法
                            //获取类上的实例变量集合
                            var count : UInt32 = 0
                            let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground")!, &count)
                            for i in 0..<count{
                                //获取单个实例
                                let ivar = ivars[Int(i)]
                                //获取实例属性
                                //实例名称
                                let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
                                //实例类型
                                let ivarType = NSString(CString: ivar_getTypeEncoding(ivar), encoding: NSUTF8StringEncoding)
                                printLog("name=\(ivarName),type=\(ivarType)")
                                //设置badge的背景图片
                                if ivarName!.isEqualToString("_image"){
                                    badgeViewChild.setValue(UIImage(named: "main_badge"), forKeyPath: ivarName as! String)
                                }
                                
                            }
                            
                        }
                    }
                }
            }
        }
    }

    }
}